import 'dart:io';
import 'dart:typed_data';
import 'package:dio/dio.dart';
import 'package:multi_image_picker/multi_image_picker.dart';
import 'package:wanchong/conf.dart';
import 'package:wanchong/utils/http.dart';
import 'package:path_provider/path_provider.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';

class FileUtils {
  //获得应用文档目录
  _getPath() async {
    final Directory _directory = await getApplicationDocumentsDirectory();
    final Directory _imageDirectory =
        await new Directory('${_directory.path}/image/')
            .create(recursive: true);
    _imgPath = _imageDirectory.path;
    // final Directory _directory
    print('本次获得路径：${_imageDirectory.path}');
  }

  //上传图片时压缩后的路径
  String _imgPath = "";
  // String _cachePath = "";

  static FileUtils _instance;
  static FileUtils getInstance() {
    if (_instance == null) {
      _instance = FileUtils();
    }
    return _instance;
  }

  upload(Asset file, Function onSuccess, Function onFailed,
      Function onProcess) async {
    if (_imgPath == "") {
      final Directory _directory = await getApplicationDocumentsDirectory();
      final Directory _imageDirectory =
          await new Directory('${_directory.path}/image/')
              .create(recursive: true);
      _imgPath = _imageDirectory.path;
      // print('本次获得路径：${_imageDirectory.path}');
    }
    var now = DateTime.now().millisecondsSinceEpoch;
    ByteData byteData = await file.requestOriginal();
    List<int> imageData = byteData.buffer.asUint8List();
    // var name = now + i;
    var result =
        await FlutterImageCompress.compressWithList(imageData, quality: 60);
    File imageFile = new File('${_imgPath}Image_${now.toString()}.png')
      ..writeAsBytesSync(result);
    var fileName = "Image_${now.toString()}.png";
    // print(_imgPath);
    // _getPath();
    Http.getInstance().upload(uploadUrl, UploadFileInfo(imageFile, fileName),
        (r, t) {
      onProcess(r, t);
    }, (r) {
      onSuccess(r);
    });
  }

  uploadFile(File file, Function onSuccess, {Function onProcess}) async {
    if (_imgPath == "") {
      final Directory _directory = await getApplicationDocumentsDirectory();
      final Directory _imageDirectory =
          await new Directory('${_directory.path}/image/')
              .create(recursive: true);
      _imgPath = _imageDirectory.path;
      // print('本次获得路径：${_imageDirectory.path}');
    }
    var now = DateTime.now().millisecondsSinceEpoch;
    List<int> imageData = await file.readAsBytes();
    // var name = now + i;
    var result =
        await FlutterImageCompress.compressWithList(imageData, quality: 60);
    File imageFile = new File('${_imgPath}Image_${now.toString()}.png')
      ..writeAsBytesSync(result);
    var fileName = "Image_${now.toString()}.png";
    Http.getInstance().upload(uploadUrl, UploadFileInfo(imageFile, fileName),
        (r, t) {
      if (onProcess!=null) {
        onProcess(r, t);
      }
    }, (r) {
      onSuccess(r);
    });
  }
  ///加载缓存
  Future<double> loadCache() async {
    try {
      Directory tempDir = await getTemporaryDirectory();
      double value = await _getTotalSizeOfFilesInDir(tempDir);
      /*tempDir.list(followLinks: false,recursive: true).listen((file){
          //打印每个缓存文件的路径
        print(file.path);
      });*/
      print('临时目录大小: ' + value.toString());
      return value;
      // setState(() {
      //   _cacheSizeStr = _renderSize(value);
      // });
    } catch (err) {
      print(err);
    }
  }


  Future<double> _getTotalSizeOfFilesInDir(final FileSystemEntity file) async {
    try {
      if (file is File) {
            int length = await file.length();
            return double.parse(length.toString());
          }
      if (file is Directory) {
            final List<FileSystemEntity> children = file.listSync();
            double total = 0;
            if (children != null)
              for (final FileSystemEntity child in children)
                total += await _getTotalSizeOfFilesInDir(child);
            return total;
          }
      return 0;
    } catch (e) {
      print(e);
      return 0;
    }
  }
  
  ///递归方式删除目录
  Future<Null> delDir(FileSystemEntity file) async {
    try {
      if (file is Directory) {
            final List<FileSystemEntity> children = file.listSync();
            for (final FileSystemEntity child in children) {
              await delDir(child);
            }
          }
      await file.delete();
    } catch (e) {
      print(e);
    }
  }
}
